/*
 * Created by 岱青海蓝信息系统(北京)有限公司 on 17-7-12 下午3:55
 * Copyright (c) 2017. All rights reserved.
 */

package com.example.dqhl.jdmetro.activities;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.dqhl.jdmetro.R;
import com.example.dqhl.jdmetro.adapter.live.LiveCommentAdapater;
import com.example.dqhl.jdmetro.base.BaseActivity;
import com.example.dqhl.jdmetro.bean.live.LiveDetail;
import com.example.dqhl.jdmetro.bean.live.LiveDetailComment;
import com.example.dqhl.jdmetro.config.Config;
import com.example.dqhl.jdmetro.utils.Dlog;
import com.example.dqhl.jdmetro.utils.JsonUtils;
import com.example.dqhl.jdmetro.utils.Toastutils;
import com.example.dqhl.jdmetro.utils.recycleview.ConsulationRecycleViewLayoutManager;
import com.google.gson.Gson;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.header.progresslayout.ProgressLayout;
import com.squareup.picasso.Picasso;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import fm.jiecao.jcvideoplayer_lib.JCUserAction;
import fm.jiecao.jcvideoplayer_lib.JCUserActionStandard;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard;

/**
 * description:直播详情
 * autour:guanluocang
 * date:17/7/12 15:55
 */
public class LiveDetailActivity extends BaseActivity {

    @Bind(R.id.live_refresh_layout)
    TwinklingRefreshLayout live_refresh_layout;

    private Context context;
    private String seed_id;//视频id
    @Bind(R.id.jc_video)//视频播放器
            JCVideoPlayerStandard jc_video;
    private String upfile;//视频地址
    private String title;//视频地址;
    private String pic;//视频图片
    private int seedPageViews;//浏览量
    private int seedCollectCount;//收藏量
    private int seedLikeCount;//点赞量

    @Bind(R.id.tv_title)
    TextView tv_title;//标题
    @Bind(R.id.tv_seedPageViews)
    TextView tv_seedPageViews;//浏览量
    @Bind(R.id.tv_seedCollectCount)
    TextView tv_seedCollectCount;//收藏量
    @Bind(R.id.tv_seedLikeCount)
    TextView tv_seedLikeCount;//点赞量
    @Bind(R.id.iv_collect)
    ImageView iv_collect;//收藏
    private int is_collect = 0;// 是否收藏
    @Bind(R.id.iv_like)//点赞
            ImageView iv_like;
    private int is_like = 0;

    @Bind(R.id.et_speakContent)
    EditText et_speakContent;//评论内容
    @Bind(R.id.tv_sendMsg)
    TextView tv_sendMsg;//发送按钮

    //评论RecycleView
    @Bind(R.id.rv_live_comment)
    RecyclerView rv_live_comment;
    private LiveCommentAdapater liveCommentAdapter;
    private List<LiveDetailComment.DataBean> liveComment = new ArrayList<>();
    private LiveDetail liveDetail;
    @Bind(R.id.tv_noInfo)
    TextView tv_noInfo;
    private int page = 1;

    @Override
    public void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_live_detail);
        initTitleBar(R.string.txt_liveDetail);
        setRightTextVisibility(View.GONE);
        context = this;
        ButterKnife.bind(this);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    @Override
    public void initData() {
        seed_id = getIntent().getStringExtra("id");
        ConsulationRecycleViewLayoutManager layoutManager = new ConsulationRecycleViewLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rv_live_comment.setLayoutManager(layoutManager);
        rv_live_comment.setItemAnimator(new DefaultItemAnimator());
        rv_live_comment.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        rv_live_comment.setNestedScrollingEnabled(false);
//        rv_live_comment.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
//        rv_live_comment.setLoadingMoreProgressStyle(ProgressStyle.Pacman);
//        rv_live_comment.setArrowImageView(R.drawable.iconfont_downgrey);
        ProgressLayout headerView = new ProgressLayout(this);
        live_refresh_layout.setHeaderView(headerView);
        live_refresh_layout.setOverScrollRefreshShow(false);
        doContent();
        doCollect(0);
        doLike(0);
        doComment(page);
    }

    /**
     * 获取标题内容
     */
    private void doContent() {
        Dlog.e("" + user.getId_auth());
        Dlog.e("" + seed_id);
        final RequestParams params = new RequestParams(Config.live_detail_content);
        params.addBodyParameter("id_auth", user.getId_auth());
        params.addBodyParameter("seed_id", seed_id);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e("直播详情" + result);
                int errCode = JsonUtils.getErrCode(result);
                String data = JsonUtils.getData(result);
                String errMsg = JsonUtils.getErrMsg(result);
                if (errCode == 200) {
                    liveDetail = new Gson().fromJson(result, LiveDetail.class);
                    upfile = liveDetail.getData().getUpfile();
                    title = liveDetail.getData().getTitle();
                    pic = liveDetail.getData().getPic();
                    seedPageViews = liveDetail.getData().getSeed_pageviews();

                    tv_title.setText(title);
                    //浏览量
                    tv_seedPageViews.setText(seedPageViews + "");
                    //视频播放地址
                    jc_video.setUp(Config.pic_base_url + upfile
                            , JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL, title);
                    //视频暂未播放静止页面
                    Picasso.with(LiveDetailActivity.this)
                            .load(Config.pic_base_url + pic)
                            .into(jc_video.thumbImageView);

                    JCVideoPlayer.setJcUserAction(new MyUserActionStandard());


                } else {
                    Toastutils.show(errMsg);
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
            }
        });
    }

    /**
     * 获取评论列表
     */
    public void doComment(int pages) {
        RequestParams params = new RequestParams(Config.live_detail_comment);
        params.addBodyParameter("id_auth", user.getId_auth());
        params.addBodyParameter("seed_id", seed_id);
        params.addBodyParameter("page", pages + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                int errCode = JsonUtils.getErrCode(result);
                String errMsg = JsonUtils.getErrMsg(result);
                if (errCode == 200) {
                    LiveDetailComment liveDetailComment = new Gson().fromJson(result, LiveDetailComment.class);
                    liveComment = liveDetailComment.getData();
                    if (liveComment.size() == 0 || liveComment == null) {
                        tv_noInfo.setVisibility(View.VISIBLE);
                        rv_live_comment.setVisibility(View.GONE);
                    } else {
                        tv_noInfo.setVisibility(View.GONE);
                        rv_live_comment.setVisibility(View.VISIBLE);
                        liveCommentAdapter = new LiveCommentAdapater(context, liveComment, new LiveCommentAdapater.OnFabulousListener() {
                            @Override
                            public void onFabulous(int position) {
                                doFabulous(position);
                            }
                        }, new LiveCommentAdapater.OnDeleteListener() {
                            @Override
                            public void onDelete(int position) {
                                doDelete(position);
                            }
                        });
                        rv_live_comment.setAdapter(liveCommentAdapter);
                        liveCommentAdapter.notifyDataSetChanged();
                    }
                } else {
                    Toastutils.show(errMsg);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    /**
     * 加载更多
     */
    public void loadMoreComment(int pages) {
        RequestParams params = new RequestParams(Config.live_detail_comment);
        params.addBodyParameter("id_auth", user.getId_auth());
        params.addBodyParameter("seed_id", seed_id);
        params.addBodyParameter("page", pages + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                int errCode = JsonUtils.getErrCode(result);
                String errMsg = JsonUtils.getErrMsg(result);
                if (errCode == 200) {
                    LiveDetailComment liveDetailComment = new Gson().fromJson(result, LiveDetailComment.class);
                    liveComment.addAll(liveDetailComment.getData());
                    rv_live_comment.setAdapter(liveCommentAdapter);
                    liveCommentAdapter.notifyDataSetChanged();
                } else {
                    Toastutils.show(errMsg);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    public void initListener() {
        tv_sendMsg.setOnClickListener(this);
        iv_collect.setOnClickListener(this);
        iv_like.setOnClickListener(this);
        live_refresh_layout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
                page = 1;
                doComment(page);
                doCollect(0);
                doLike(0);
                refreshLayout.finishRefreshing();
            }

            @Override
            public void onLoadMore(final TwinklingRefreshLayout refreshLayout) {
                page++;
                loadMoreComment(page);
                refreshLayout.finishLoadmore();
            }
        });

    }

    @Override
    protected void onPause() {
        super.onPause();
        JCVideoPlayer.releaseAllVideos();
    }

    @Override
    public void onBackPressed() {
        if (JCVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    /**
     * 发送信息
     */
    private void doSendMsg() {
        String msg = et_speakContent.getText().toString().trim();
        if (!TextUtils.isEmpty(msg)) {
            final RequestParams params = new RequestParams(Config.live_comment_list);
            params.addBodyParameter("seed_id", seed_id);
            params.addBodyParameter("id_auth", user.getId_auth());
            params.addBodyParameter("comment_content", msg);
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Dlog.e("评论成功" + result);
                    int errCode = JsonUtils.getErrCode(result);
                    if (errCode == 200) {
                        et_speakContent.setText("");
                        InputMethodManager imm1 = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm1.hideSoftInputFromWindow(et_speakContent.getWindowToken(), 0);//从控件所在的窗口中隐藏
                        page = 1;
                        doComment(page);
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });
        } else {
            Toastutils.show("请输入内容");
        }
    }

    /**
     * 点赞
     */

    public void doFabulous(int position) {
        showLoadingBar("");
        RequestParams params = new RequestParams(Config.live_comment_fabulous);
        params.addBodyParameter("id_auth", user.getId_auth());
        params.addBodyParameter("seed_comment_id", liveComment.get(position).getComment_id());
        // 赞的状态：0-未赞，1-已赞
        if (liveComment.get(position).getIs_comment_like_count() == 1) {
            params.addBodyParameter("state", 2 + "");
        } else {
            params.addBodyParameter("state", 1 + "");
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e("点赞" + result);
                int errCode = JsonUtils.getErrCode(result);
                if (errCode == 200) {
                    doComment(page);
                    liveCommentAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                hideLoadingBar();
            }
        });
    }

    /**
     * 删除
     */
    public void doDelete(int position) {
        if (liveComment.get(position).getComment_id_auth().equals(user.getId_auth())) {
            showLoadingBar("");
            RequestParams params = new RequestParams(Config.live_comment_delete);
            params.addBodyParameter("id_auth", user.getId_auth());
            params.addBodyParameter("comment_id", liveComment.get(position).getComment_id());
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Dlog.e("删除" + result);
                    int errCode = JsonUtils.getErrCode(result);
                    if (errCode == 200) {
                        doComment(page);
                        liveCommentAdapter.notifyDataSetChanged();
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {
                    hideLoadingBar();
                }
            });
        } else {
            Toastutils.show("只可删除私有评论");
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_sendMsg:
                doSendMsg();
                break;
            //对视频点赞
            case R.id.iv_like:
                doLike(is_like);
                break;
            //对视频收藏
            case R.id.iv_collect:
                doCollect(is_collect);
                break;
        }
    }

    //收藏
    private void doCollect(int is_collects) {
        RequestParams params = new RequestParams(Config.live_collect);
        params.addBodyParameter("id_auth", user.getId_auth());
        params.addBodyParameter("seed_id", seed_id);
        // 收藏的状态：0-未赞，1-已赞
        // 赞的状态：0-未赞，1-已赞    1点赞   2取消点赞  无操作传0
        params.addBodyParameter("state", is_collects + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e(result);
                int errCode = JsonUtils.getErrCode(result);
                String data = JsonUtils.getData(result);
                if (errCode == 200) {
                    seedCollectCount = Integer.parseInt(JsonUtils.getInfo(data, "seed_collect"));
                    //收藏量
                    tv_seedCollectCount.setText(seedCollectCount + "");
                    is_collect = Integer.parseInt(JsonUtils.getInfo(data, "is_collect"));
                    //是否已收藏
                    if (is_collect == 0) {
                        is_collect = 1;
                        iv_collect.setImageResource(R.drawable.ic_live_like);
                    } else {
                        is_collect = 2;
                        iv_collect.setImageResource(R.drawable.ic_live_like_pressed);
                    }
                } else if (errCode == 201) {
                    seedCollectCount = Integer.parseInt(JsonUtils.getInfo(data, "seed_collect"));
                    //收藏量
                    tv_seedCollectCount.setText(seedCollectCount + "");
                    is_collect = Integer.parseInt(JsonUtils.getInfo(data, "is_collect"));
                    //是否已收藏
                    if (is_collect == 0) {
                        is_collect = 1;
                        iv_collect.setImageResource(R.drawable.ic_live_like);
                    } else {
                        is_collect = 2;
                        iv_collect.setImageResource(R.drawable.ic_live_like_pressed);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    //点赞
    private void doLike(int is_likes) {
        RequestParams params = new RequestParams(Config.live_fabulous);
        params.addBodyParameter("id_auth", user.getId_auth());
        params.addBodyParameter("seed_id", seed_id);
        // 赞的状态：0-未赞，1-已赞    1点赞   2取消点赞  无操作传0
        params.addBodyParameter("state", is_likes + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e(result);
                int errCode = JsonUtils.getErrCode(result);
                String data = JsonUtils.getData(result);
                if (errCode == 200) {
                    seedLikeCount = Integer.parseInt(JsonUtils.getInfo(data, "count_praise"));
                    //点赞量
                    tv_seedLikeCount.setText(seedLikeCount + "");
                    is_like = Integer.parseInt(JsonUtils.getInfo(data, "is_praise"));
                    //是否已点赞 0未点赞 1已点赞
                    if (is_like == 0) {
                        is_like = 1;
                        iv_like.setImageResource(R.drawable.ic_fabulous);
                    } else {
                        is_like = 2;
                        iv_like.setImageResource(R.drawable.ic_fabulous_pressed);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }


    class MyUserActionStandard implements JCUserActionStandard {

        @Override
        public void onEvent(int type, String url, int screen, Object... objects) {
            switch (type) {
                case JCUserAction.ON_CLICK_START_ICON:
                    Log.i("USER_EVENT", "ON_CLICK_START_ICON" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
                    break;
                case JCUserAction.ON_CLICK_START_ERROR:
                    Log.i("USER_EVENT", "ON_CLICK_START_ERROR" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
                    break;
                case JCUserAction.ON_CLICK_START_AUTO_COMPLETE:
                    Log.i("USER_EVENT", "ON_CLICK_START_AUTO_COMPLETE" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
                    break;
                case JCUserAction.ON_CLICK_PAUSE:
                    Log.i("USER_EVENT", "ON_CLICK_PAUSE" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
                    break;
                case JCUserAction.ON_CLICK_RESUME:
                    Log.i("USER_EVENT", "ON_CLICK_RESUME" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
                    break;
                case JCUserAction.ON_SEEK_POSITION:
                    Log.i("USER_EVENT", "ON_SEEK_POSITION" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
                    break;
                case JCUserAction.ON_AUTO_COMPLETE:
                    Log.i("USER_EVENT", "ON_AUTO_COMPLETE" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
                    break;
                case JCUserAction.ON_ENTER_FULLSCREEN:
                    Log.i("USER_EVENT", "ON_ENTER_FULLSCREEN" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
                    break;
                case JCUserAction.ON_QUIT_FULLSCREEN:
                    Log.i("USER_EVENT", "ON_QUIT_FULLSCREEN" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
                    break;
                case JCUserAction.ON_ENTER_TINYSCREEN:
                    Log.i("USER_EVENT", "ON_ENTER_TINYSCREEN" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
                    break;
                case JCUserAction.ON_QUIT_TINYSCREEN:
                    Log.i("USER_EVENT", "ON_QUIT_TINYSCREEN" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
                    break;
                case JCUserAction.ON_TOUCH_SCREEN_SEEK_VOLUME:
                    Log.i("USER_EVENT", "ON_TOUCH_SCREEN_SEEK_VOLUME" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
                    break;
                case JCUserAction.ON_TOUCH_SCREEN_SEEK_POSITION:
                    Log.i("USER_EVENT", "ON_TOUCH_SCREEN_SEEK_POSITION" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
                    break;

                case JCUserActionStandard.ON_CLICK_START_THUMB:
                    Log.i("USER_EVENT", "ON_CLICK_START_THUMB" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
                    break;
                case JCUserActionStandard.ON_CLICK_BLANK:
                    Log.i("USER_EVENT", "ON_CLICK_BLANK" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
                    break;
                default:
                    Log.i("USER_EVENT", "unknow");
                    break;
            }
        }
    }
}
